/**
 * 
 */
package org.t2.backstage.module.player;

import org.banish.sql.core.util.QuerySet;
import org.gaming.backstage.PageData;
import org.gaming.backstage.interceptor.RoleContext;
import org.gaming.backstage.module.user.model.User;
import org.gaming.backstage.module.user.service.UserService;
import org.gaming.service.advice.ResponseResult;
import org.gaming.service.apidoc.annotation.ApiDocument;
import org.gaming.service.asserts.Asserts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.t2.backstage.module.TipsCode;
import org.t2.backstage.module.gameserver.model.GameServer;
import org.t2.backstage.module.gameserver.service.GameServerService;
import org.t2.backstage.module.player.form.PlayerSwitchForm;
import org.t2.backstage.module.player.model.Player;
import org.t2.backstage.module.player.model.PlayerSwitch;
import org.t2.backstage.module.player.query.PlayerSwitchQuery;
import org.t2.backstage.module.player.service.PlayerService;
import org.t2.backstage.module.player.service.PlayerSwitchService;
import org.t2.backstage.util.T2HttpUtil;

import sh.t2.share.apiutil.GameApi;
import sh.t2.share.module.player.PlayerApiProtocol.PlayerDeleteSwitchRequest;
import sh.t2.share.module.player.PlayerApiProtocol.PlayerDeleteSwitchResponse;
import sh.t2.share.module.player.PlayerApiProtocol.PlayerSwitchRequest;
import sh.t2.share.module.player.PlayerApiProtocol.PlayerSwitchResponse;

/**
 * 
 */
@Controller
public class PlayerSwitchController {

	private static Logger logger = LoggerFactory.getLogger(PlayerSwitchController.class);
	
	@Autowired
	private PlayerSwitchService playerSwitchService;
	@Autowired
	private UserService userService;
	@Autowired
	private PlayerService playerService;
	@Autowired
	private GameServerService gameServerService;
	
	@ApiDocument("请求玩家账号切换数据")
	@RequestMapping(value = "/playerSwitch/data.auth")
	@ResponseBody
	public PageData<PlayerSwitch> data(PlayerSwitchQuery query) {
		QuerySet querySet = new QuerySet();
		if(query.getOriPlayerId() > 0) {
			querySet.addCondition("ori_player_id = ?", query.getOriPlayerId());
		}
		if(query.getDestPlayerId() > 0) {
			querySet.addCondition("dest_player_id = ?", query.getDestPlayerId());
		}
		querySet.limit(query.getPage(), query.getLimit());
		querySet.formWhere();
		return playerSwitchService.query(querySet);
	}
	
	@ApiDocument("新增账号切换记录")
	@RequestMapping(value = "/playerSwitch/save.authw")
	@ResponseBody
	public PlayerSwitch saveData(PlayerSwitchForm form) {
		RoleContext roleContext = userService.getCurrUser();
		User user = userService.getById(roleContext.getId());
		Asserts.isTrue(user.isSuperUser(), TipsCode.NO_SUPERUSER);
		
		PlayerSwitch playerSwitch = null;
		try {
			
			Player oriPlayer = playerService.getEntity(form.getOriPlayerId());
			Player destPlayer = playerService.getEntity(form.getDestPlayerId());
			
			Asserts.isTrue(oriPlayer != null, TipsCode.PLAYER_NOT_EXIST, form.getOriPlayerId());
			Asserts.isTrue(destPlayer != null, TipsCode.PLAYER_NOT_EXIST, form.getDestPlayerId());
			Asserts.isTrue(oriPlayer.getPlatformId() == destPlayer.getPlatformId(), TipsCode.PLAYER_MUST_SAME_PLATFORM);
			Asserts.isTrue(oriPlayer.getServerId() == destPlayer.getServerId(), TipsCode.PLAYER_MUST_SAME_SERVER);
			Asserts.isTrue(oriPlayer.getId() != destPlayer.getId(), TipsCode.PLAYER_SWITCH_NOT_SAME);
			
			playerSwitch = new PlayerSwitch();
			playerSwitch.setOriPlayerId(form.getOriPlayerId());
			playerSwitch.setDestPlayerId(form.getDestPlayerId());
			playerSwitch.setUserId(user.getId());
			playerSwitch.setUserName(user.getName());
			playerSwitchService.insert(playerSwitch);
			
			GameServer gameServer = gameServerService.getByPlatformAndServer(oriPlayer.getPlatformId(), oriPlayer.getServerId());
			
			PlayerSwitchRequest request = new PlayerSwitchRequest();
			request.oriPlayerId = form.getOriPlayerId();
			request.destPlayerId = form.getDestPlayerId();
			ResponseResult<PlayerSwitchResponse> response = T2HttpUtil.jsonPost(gameServer, GameApi.playerSwitch, request, PlayerSwitchResponse.class);
			
			if(response.getCode() == 0) {
				logger.info("账号切换发送成功，来源ID{}，目标ID{}", form.getOriPlayerId(), form.getDestPlayerId());
			} else {
				playerSwitchService.delete(playerSwitch);
				logger.error("账号切换发送失败，来源ID{}，目标ID{}", form.getOriPlayerId(), form.getDestPlayerId());
			}
		} catch (Exception e) {
			Asserts.isTrue(false, TipsCode.PLAYER_SWITCH_ONLY);
		}
		return playerSwitch;
	}
	
	@ApiDocument("删除账号切换记录")
	@RequestMapping(value = "/playerSwitch/delete.authw")
	@ResponseBody
	public void delete(@RequestParam("id") long id) {
		PlayerSwitch playerSwitch = playerSwitchService.getEntity(id);
		Asserts.isTrue(playerSwitch != null, TipsCode.PLAYER_SWITCH_NOT_FOUND, id);
		
		Player oriPlayer = playerService.getEntity(playerSwitch.getOriPlayerId());
		GameServer gameServer = gameServerService.getByPlatformAndServer(oriPlayer.getPlatformId(), oriPlayer.getServerId());
		
		PlayerDeleteSwitchRequest request = new PlayerDeleteSwitchRequest();
		request.oriPlayerId = playerSwitch.getOriPlayerId();
		request.destPlayerId = playerSwitch.getDestPlayerId();
		ResponseResult<PlayerDeleteSwitchResponse> response = T2HttpUtil.jsonPost(gameServer, GameApi.playerDeleteSwitch, request, PlayerDeleteSwitchResponse.class);
		if(response.getCode() == 0) {
			playerSwitchService.delete(playerSwitch);
		} else {
			logger.error("账号切换取消失败，来源ID{}，目标ID{}", playerSwitch.getOriPlayerId(), playerSwitch.getDestPlayerId());
		}
	}
}
